﻿using Back_end.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Back_end
{
    public class MvcApplication : System.Web.HttpApplication
	{
		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();
			GlobalConfiguration.Configure(WebApiConfig.Register);
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);

			ApplicationDbContext db = new ApplicationDbContext();
			using (ApplicationUserManager UserManager =
				new ApplicationUserManager(
					new UserStore<ApplicationUser>(db)))
			{
				if (UserManager.FindByName("SuperUser") == null)
				{
					using (var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)))
					{
						var user = new ApplicationUser
						{
							UserName = "SuperUser",
							Email = "lzxglhf@live.com",
							Gender = "男",
							RealName = "小明",
							Location = "杭州",
							TodayCount = 0,
							TotleCredit = 100,
							Credit = 0,
							RegisterDate = DateTime.Now,
							HadAuthentication = true,
							EmailConfirmed = true,
							LastestDate = null,
							AvatarPath = "/Image/AdminAvatar.png",
							Complaints = null
						};

						var result = UserManager.Create(user, "Abc_123");
						if (result.Succeeded)
						{
							rm.Create(new IdentityRole("SuperUser"));
							rm.Create(new IdentityRole("Admin"));

							UserManager.AddToRoles(user.Id, new string[] { "SuperUser", "Admin" });
						}
						db.SaveChanges();
					}
				}
			}

			TimeTask.Instance().ExecuteTask += new System.Timers.ElapsedEventHandler(GlobalExecuteTask);
			TimeTask.Instance().Start();
		}

		void GlobalExecuteTask(object sender, System.Timers.ElapsedEventArgs e)
		{
			using (ApplicationDbContext db = new ApplicationDbContext())
			{
				if (db.Complaints.Count() != 0)
				{
					foreach (var c in db.Complaints)
					{
						if (c.Weight >= 1)
							c.Weight -= 0.5;
					}
				}
				db.SaveChanges();
			}
		}

		public static readonly string[] Levels = new string[]
		{
			"Lv1",
			"Lv2",
			"Lv3",
			"Lv4",
			"Lv5"
		};
	}
}
